/**
 *
 * Created by shenzaifang on 2019-04-09
 */
import {
    toast,
    promptBox
} from 'nc-lightapp-front';
import {Maybe} from 'src/hrpub/common/utils/utils'
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import {getAppPageConfig} from 'src/hrpub/common/utils/utils';

let appConfig = getAppPageConfig();
if (new RegExp(/(localhost|127\.0\.0\.1):3006/g).test(window.location.href)) {
    appConfig = {
        pagecode: '60092050nccloud',
        appcode: '60092050'
    }
}

export const COMMON = {
    appConfig,
    tableId: 'list',
    searchId: 'query',
    searchId2: 'multiadd',
    formId: 'card',
    formId2: 'card_batch',
    addBranch: 'list_batch',
    pageInfo: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        totalPage: 1
    }, // 主页面表格的分页信息
    pageMain: 'main', // 首页
    pageDetail: 'detail', // 详情页
    pageAdd: 'add', // 详情页
    orderStatus: ['-1', '3'], // 单据状态 '-1'：自由态； '3'：提交；'2'：审批进行中；'1'：审批通过；'0'：审批不通过；'102'：已执行
    orderTimeRange: 'oneWeek', // 时间范围
    printUrl: '/nccloud/hrtrn/transapply/TransPrintAction.do', // 打印输出url
};


export function changeData(dataRows, transfer) {
    dataRows.forEach(item => {
        let val = item.values.trial_flag.value;
        if (val) {
            item.values.trial_flag.value = transfer.language['gx6008-000092']
        } else {
            item.values.trial_flag.value = transfer.language['gx6008-000093']
        }
    });
}

/**
 * 获取表头
 * @param tmp
 * @returns {Array}
 */
export function getTableTmp(tmp) {
    let tableTmp = [];

    let visibleCol = [];

    tmp.items.forEach((item) => {
        if (item.visible && item.attrcode !== 'opr' && item.attrcode !== 'file') {
            visibleCol.push(item);
        }
    });

    visibleCol.forEach((col) => {
        tableTmp.push(col.label);
    });

    return tableTmp
}

/**
 * 修改 操作列 不打印/输出
 * @param meta
 */
export function changeMeta(meta) {
    meta.items.forEach(item => {
        if (item.attrcode === 'file' || item.attrcode === 'opr') {
            item.visible = false
        }
    });
}

/**
 * 获取被选中的行数据
 * @param props
 * @param key 要获取的数据
 * @returns {Array}
 */
export function getCheckedRows(props, key) {
    let billids = [];
    let rows = props.editTable.getCheckedRows(COMMON.tableId);
    if (rows.length > 0) {
        rows.forEach(item => {
            let values = item.data.values;
            if (values.hasOwnProperty(key)) {
                billids.push(values[key].value);
            }
        })
    }
    return billids.length > 0 && billids
}

/**
 * 获取table中的数据
 * @param props
 * @param key 要获取的数据
 * @returns {Array}
 */
export function getAllRowsVal(props, key) {
    let billids = [];
    let rows = props.editTable.getAllRows(COMMON.tableId);
    if (rows.length > 0) {
        rows.forEach(item => {
            let values = item.data.values;
            if (values.hasOwnProperty(key)) {
                billids.push(values[key].value);
            }
        })
    }
    return billids
}

/**
 * 设置fo人民表单的不可编辑性
 * @param props
 * @param meta 要获取的数据
 * @param formId 要获取的数据
 */
export function setFormDisabled(props, meta, formId) {
    if (typeof meta !== "object") return;
    for (let key in meta) {
        let template = meta[key];
        if (Array.isArray(template.items)) {
            template.items.forEach(item => {
                props.form.setFormItemsDisabled(formId, {[item.attrcode]: item.disabled})
            })
        }
    }
}

/**

 * 设置fo人民表单的不可编辑性
 * @param toast
 * @param billids 要获取的数据
 * @param transfer 要获取的数据
 * @returns {boolean}
 */
export function checkBillId(toast, billids, transfer) {
    let flag = false;
    if (Array.isArray(billids) && billids.length > 0) {
        flag = true
    }
    if (typeof billids === 'string' && billids.length > 0) {
        flag = true;
    }
    if (!flag) {
        toast({
            color: 'danger',
            content: transfer.language['gx6008-000100']
        });
    }
    return flag
}

/**
 * 获取billid
 * @param record
 * @returns {any}
 */
export function getBillid(record) {
    if (Maybe.of(record).getValue(['values', 'pk_hi_stapply', 'value'])) {
        return record.values.pk_hi_stapply.value
    }
    return null;
}

/**
 * 获取billtype
 * @param record
 * @returns {any}
 */
export function getBilltype(record) {
    let transtype = Maybe.of(record).getValue(['values', 'transtype', 'value']);
    let pk_billtype = Maybe.of(record).getValue(['values', 'pk_billtype', 'value']);
    return transtype || pk_billtype;
}

/**
 * 向模板添加queryCondition空对象
 * @param template
 */
export function addTempleteQueCon(template) {
    let formArr = deepCopy(template.formrelation[COMMON.formId]);
    let formArr2 = deepCopy(template.formrelation[COMMON.formId2]);
    formArr.push(COMMON.formId);
    formArr2.push(COMMON.formId2);
    formArr.concat(formArr2).forEach(formId => {
        template[formId].items.forEach(item => {
            if (item.itemtype === 'refer') {
                if (!item.hasOwnProperty('queryCondition')) {
                    item.queryCondition = {};
                }
            }
        })
    })
}

export function getUrlParam(props) {
    const {getUrlParam} = props;
    let scene = getUrlParam('scene');
    let id = getUrlParam('id');
    let status = getUrlParam('status');
    return {fromScene: scene === 'approvesce', id, status}
}

// 更新按钮状态
export function updateButtonStatus(props, billid) {
    let disabledFlag = !billid;
    props.button.setButtonDisabled({
        // "add_d":disabledFlag,
        "edit_d": disabledFlag,
        "del_d": disabledFlag,
        "commit_d": disabledFlag,
        "refresh_d": disabledFlag,
        "more_d": disabledFlag,
        "file_d": disabledFlag,
    });
    let isCenter = getUrlParam(props).fromScene;
    if (!isCenter && getUrlParam(props).status) {
        isCenter = 'approvesce';
    }
    props.button.setButtonVisible({
        "add_d": !isCenter,
        "del_d": !isCenter,
        "commit_d": !isCenter,
        "recover_d": !isCenter,
        "checkOpini": !isCenter,
        // "psncard" : isCenter
    });
}

export async function toastMsg(res, transfer, beSureFun, cancelFun) {
    if (!res.data) return;
    if (res.data.warning) {
        toast({
            color: 'warning',
            content: res.data.warningMsg
        });
    }
    if (res.data.tip) {
        toast({
            color: 'warning',
            content: res.data.tipMsg
        });
    }
    if (res.data.confirm) {
        await new Promise(resolve => {
            promptBox({
                color: "warning",
                title: transfer.language['gx6008-000018'], /* 国际化处理： 提示*/
                content: res.data.confirmMsg,
                beSureBtnClick: () => {
                    if (beSureFun && typeof beSureFun === 'function') {
                        beSureFun()
                    }
                    resolve();
                },
                cancelBtnClick: () => {
                    if (cancelFun && typeof cancelFun === 'function') {
                        cancelFun()
                    }
                    resolve();
                },
                closeModalEve: () => {
                    if (cancelFun && typeof cancelFun === 'function') {
                        cancelFun()
                    }
                    resolve();
                }
            });
        });
    }
}

export function setFormState(props, res) {
    if (!res) return;
    if (!res.data) return;
    //设置form
    let visible = {}, disable = {}, required = {};
    Object.keys(res.data).forEach(id => {
        let template = res.data[id];
        if (typeof template !== 'object') return;
        if (!template.hasOwnProperty('items')) return;
        let items = template.items;
        if (!Array.isArray(items)) return;
        items.forEach(item => {
            let attrcode = item.attrcode;
            visible[attrcode] = item.visible;
            required[attrcode] = item.required;
            // 卡片页点击新增根据  isBillCodeEditable 这个字段判断是否可编辑
            if (attrcode === 'bill_code') return;
            disable[attrcode] = item.disabled;
        })
    });
    let moduleId = COMMON.formId;
    props.form.setFormItemsVisible(moduleId, visible);
    props.form.setFormItemsDisabled(moduleId, disable);
    props.form.setFormItemsRequired(moduleId, required);
}
